
const {ccclass, property} = cc._decorator;

@ccclass
export default class EventMgr extends cc.Component {
    private eventMap: any = null;  // {"eventName": [ {func: 回调的函数, caller: 函数里面的this}], "eventName": [], }

    public static Instance: EventMgr = null
    onLoad() {
        if (EventMgr.Instance !== null) {
            this.destroy();
            return;
        }
        EventMgr.Instance = this;
    }

    
    public Init(): void {
        this.eventMap = {};
    }

    /**
     * 注册事件
     * @param eventName 
     * @param callback 
     * @param caller 
     */
    // func(eventName: string, udata: any)
    public AddEventListener(eventName: string, callback, caller): void {
        if (!this.eventMap[eventName]) {
            this.eventMap[eventName] = []; // [函数1()， 函数2(), ....]
        }

        var listeners = this.eventMap[eventName];
        var listenNode = {
            func: callback,
            self: caller,
        };

        listeners.push(listenNode);
    }

    /**
     * 移除事件
     * @param eventName 
     * @param callback 
     * @param caller 
     * @returns 
     */
    public RemoveEventListener(eventName: string, callback, caller): void {
        if (!this.eventMap[eventName]) {
            return;
        }

        var listeners: Array<any> = this.eventMap[eventName] as Array<any>;
        for (var i = 0; i < listeners.length; i++) {
            if (listeners[i].func === callback && listeners[i].self === caller) {
                listeners.splice(i, 1);
                // i --;
                return;
            }
        }
    }

    /**
     * 发射事件
     * @param eventName 
     * @param udata 
     * @returns 
     */
    public Emit(eventName: string, udata: any): void {
        if (!this.eventMap[eventName]) {
            return;
        }

        var listeners: Array<any> = this.eventMap[eventName] as Array<any>;
        for (var i = 0; i < listeners.length; i++) {
            listeners[i].func.call(listeners[i].self, eventName, udata);
        }
    }
}
